package com.hospital.diagnosis.module.controller;

import com.hospital.common.base.Result;
import com.hospital.common.base.ThreadAttributes;
import com.hospital.common.dto.diagnosis.module.ChatEvaluationDTO;
import com.hospital.common.pojo.TChatSession;
import com.hospital.common.utils.ThreadLocalUtils;
import com.hospital.diagnosis.module.exception.ServiceException;
import com.hospital.diagnosis.module.service.ChatEvaluationService;
import com.hospital.diagnosis.module.service.ChatService;
import com.hospital.diagnosis.module.utils.JsonUtils;
import com.hospital.diagnosis.module.vo.ChatVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

import static com.hospital.diagnosis.module.exception.enums.ExceptionCode.FORBIDDEN;
import static com.hospital.diagnosis.module.utils.WebSocketUtils.sendMessage;

@RestController
@RequestMapping("/ChatEvalution")
public class ChatEvalutionController
{
    @Autowired
    private ChatEvaluationService chatEvaluationService;
    @Autowired
    private ChatService chatService;

    /**
     * 添加会话评价
     * @param chatEvaluation
     * @return 添加结果
     */
    @PostMapping("/addChatEvaluation")
    public Result addChatEvaluation(@RequestBody @Validated ChatEvaluationDTO chatEvaluation)
    {
        ThreadAttributes ta = ThreadLocalUtils.get();
        if(ta==null||ta.getRoleType()!=0){
            throw new ServiceException(FORBIDDEN);
        }
        chatEvaluationService.addChatEvaluation(ta.getUserId(),chatEvaluation);
        //更新患者端会话列表
        List<TChatSession> chats= chatService.getChats(ta.getUserId());
        ChatVo chatVo = new ChatVo(0,chats);
        String chatsJson = JsonUtils.toJson(chatVo);
        sendMessage(ta.getUserId(),chatsJson);

        return Result.success("评价添加成功");
    }
}
